﻿using System;
using System.Xml;
using System.IO;
using System.Web;
using System.Threading;

namespace ThreadControl
{
    public class ThreadDelay
    {
        public static int SetDelay()
        {
            Random random = new Random();
            int intDelay= random.Next(3, 100);
            return intDelay;
        }

        /// <summary>
        /// 获取根目录
        /// </summary>
        public static string GetRootPath()
        {
            //NowWorkThreadCount = GetConfigNowWorkThreadCount();
            if (HttpRuntime.Cache.Get("rootPath") == null)
            {
                HttpRuntime.Cache["rootPath"] = HttpContext.Current.Server.MapPath("~/");
            }

            return HttpRuntime.Cache["rootPath"].ToString();
        }
        /// <summary>
        /// 获取正在运行的线程数
        /// </summary>
        public static int GetNowWorkThreadCount()
        {
            //NowWorkThreadCount = GetConfigNowWorkThreadCount();
       
            if (HttpRuntime.Cache.Get("currentThread") != null)
            {
                int isNumber = 0;
                if (!int.TryParse(HttpRuntime.Cache["currentThread"].ToString(), out isNumber))
                {
                    //HttpRuntime.Cache["currentThread"] =GetConfigNowWorkThreadCount();
                    HttpRuntime.Cache["currentThread"] = 0;
                }
            }
            else
            {
                //HttpRuntime.Cache["currentThread"] = GetConfigNowWorkThreadCount();
                HttpRuntime.Cache["currentThread"] = 0;
            }
            string ssd = HttpRuntime.Cache["currentThread"].ToString();
            return Convert.ToInt32(HttpRuntime.Cache["currentThread"]);
        }
        /// <summary>
        /// 获取配置文件中打开数据连接的线程数
        /// </summary>
        /// <returns></returns>
        private static int GetConfigNowWorkThreadCount()
        {
            string strWorkThreadCount = "";
            int intWorkThreadCount = 0;
            try
            {
                string strConfigPath = GetRootPath();
                using (FileStream fs = new FileStream(strConfigPath + "//setting//threadControl.config", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.Load(fs);
                    XmlNode nodeCurrentThreadCount = xmldoc.SelectSingleNode("/ThreadControl/CurrentThreadCount");
                    strWorkThreadCount = nodeCurrentThreadCount.Attributes["Count"].Value;
                    ////检测文件
                    //if (nodeCurrentThreadCount!=null)
                    //{
                    //    bool bolExist = false;
                    //    if (nodeCurrentThreadCount.Attributes != null)
                    //    {
                    //        if (nodeCurrentThreadCount.Attributes["Count"] != null)
                    //        {
                    //            strWorkThreadCount = nodeCurrentThreadCount.Attributes["Count"].Value;
                    //            bolExist = true;
                    //        }
                    //    }

                    //    if (!bolExist)
                    //    {
                    //        XmlAttribute attrCurrentThreadCount = xmldoc.CreateAttribute("Count");
                    //        attrCurrentThreadCount.Value = "0";
                    //        nodeCurrentThreadCount.AppendChild(attrCurrentThreadCount);
                    //        xmldoc.Save(fs);
                    //    }
                    //}
                    //else
                    //{
                    //    if(xmldoc.SelectNodes("/ThreadControl")!=null)
                    //    {
                    //        XmlNode rtnode = xmldoc.SelectSingleNode("/ThreadControl");
                    //        XmlNode setCurrentThreadCount = xmldoc.CreateElement("CurrentThreadCount");
                    //        XmlAttribute attrCurrentThreadCount = xmldoc.CreateAttribute("Count");
                    //        attrCurrentThreadCount.Value = "0";
                    //        setCurrentThreadCount.AppendChild(attrCurrentThreadCount);
                    //        rtnode.AppendChild(setCurrentThreadCount);
                    //    }
                    //    else
                    //    {
                    //        xmldoc.RemoveAll();
                    //        XmlNode rtnode = xmldoc.CreateElement("ThreadControl");
                    //        XmlNode setCurrentThreadCount = xmldoc.CreateElement("CurrentThreadCount");
                    //        XmlAttribute attrCurrentThreadCount = xmldoc.CreateAttribute("Count");
                    //        attrCurrentThreadCount.Value = "0";
                    //        setCurrentThreadCount.AppendChild(attrCurrentThreadCount);
                    //        rtnode.AppendChild(setCurrentThreadCount);
                    //        xmldoc.AppendChild(rtnode);
                    //    }
                    //    xmldoc.Save(fs);
                    //    fs.Close();
                    //}
                }
                int isnumber = 0;
                if (int.TryParse(strWorkThreadCount, out isnumber))
                {
                    intWorkThreadCount = int.Parse(strWorkThreadCount);
                }

                return intWorkThreadCount;
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        public static int GetMaxWorkThreadCount()
        {
            //MaxWorkThreadCount = GetConfigMaxNowWorkThreadCount();
            if (HttpRuntime.Cache.Get("maxThread") != null)
            {
                int isNumber = 0;
                if (!int.TryParse(HttpRuntime.Cache["maxThread"].ToString(), out isNumber))
                {
                    //HttpRuntime.Cache["maxThread"] = GetConfigMaxNowWorkThreadCount();
                    HttpRuntime.Cache["maxThread"] = 50;
                }
            }
            else
            {
                //HttpRuntime.Cache["maxThread"] = GetConfigMaxNowWorkThreadCount();
                HttpRuntime.Cache["maxThread"] = 50;
            }

            return Convert.ToInt32(HttpRuntime.Cache["maxThread"]);
        }
        /// <summary>
        /// 获取配置文件中打开数据连接的线程数
        /// </summary>
        /// <returns></returns>
        private static int GetConfigMaxNowWorkThreadCount()
        {
            string strMaxWorkThreadCount = "";
            int intMaxWorkThreadCount = 0;
            try
            {
                string strConfigPath = GetRootPath();
                using (FileStream fs = new FileStream(strConfigPath + "//setting//threadControl.config", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlDocument xmldoc = new XmlDocument();
                    xmldoc.Load(fs);
                    XmlNode nodeCurrentThreadCount = xmldoc.SelectSingleNode("/ThreadControl/CurrentThreadCount");
                    strMaxWorkThreadCount = nodeCurrentThreadCount.Attributes["MaxCount"].Value;
                }
                int isnumber = 0;
                if (int.TryParse(strMaxWorkThreadCount, out isnumber))
                {
                    intMaxWorkThreadCount = int.Parse(strMaxWorkThreadCount);
                }

                return intMaxWorkThreadCount;
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        public static void SetNowWorkThreadCountLiter()
        {
            try
            {
                int currentthread = GetNowWorkThreadCount();
                //string strConfigPath = GetRootPath();
                //XmlDocument xmldoc = new XmlDocument();
                //xmldoc.Load(strConfigPath + "//setting//threadControl.config");
                //XmlNode nodeCurrentThreadCount = xmldoc.SelectSingleNode("/ThreadControl/CurrentThreadCount");
                //nodeCurrentThreadCount.Attributes["Count"].Value = (currentthread + 1).ToString();
                //xmldoc.Save(strConfigPath + "//setting//threadControl.config");

                HttpRuntime.Cache["currentThread"] = currentthread + 1;

            }
            catch (Exception ex)
            {
                if (ex.GetType().Equals(typeof(System.IO.IOException)))
                {
                    System.Threading.Thread.Sleep(SetDelay());
                    SetNowWorkThreadCountLiter();
                }
                else
                {
                    throw;
                }
            }
        }

        public static void SetNowWorkThreadCountDrop()
        {
            try
            {
                if (GetNowWorkThreadCount() < 0)
                {
                    throw new Exception("操作中的线程数少于0");
                }
                int currentthread = GetNowWorkThreadCount();
                //string strConfigPath = GetRootPath();
                //XmlDocument xmldoc = new XmlDocument();
                //xmldoc.Load(strConfigPath + "//setting//threadControl.config");
                //XmlNode nodeCurrentThreadCount = xmldoc.SelectSingleNode("/ThreadControl/CurrentThreadCount");
                //nodeCurrentThreadCount.Attributes["Count"].Value = (currentthread - 1).ToString();
                //xmldoc.Save(strConfigPath + "//setting//threadControl.config");

                HttpRuntime.Cache["currentThread"] = currentthread - 1;
            }
            catch (Exception ex)
            {
                if (ex.GetType().Equals(typeof(System.IO.IOException)))
                {
                    System.Threading.Thread.Sleep(SetDelay());
                    SetNowWorkThreadCountDrop();
                }
                else
                {
                    throw;
                }
            }
        }

        /// <summary>
        /// 重置配置文件中打开数据连接的线程数
        /// </summary>
        /// <returns></returns>
        public static void ResetNowWorkThreadCount()
        {
            try
            {
                //string strConfigPath = GetRootPath();
                //XmlDocument xmldoc = new XmlDocument();
                //xmldoc.Load(strConfigPath + "//setting//threadControl.config");
                //XmlNode nodeCurrentThreadCount = xmldoc.SelectSingleNode("/ThreadControl/CurrentThreadCount");
                //nodeCurrentThreadCount.Attributes["Count"].Value = "0";
                //xmldoc.Save(strConfigPath + "//setting//threadControl.config");

                HttpRuntime.Cache["currentThread"] = 0;
            }
            catch (Exception ex)
            {
                throw;
            }
        }


    }
}